#include "MagiciteGameDrawLayer.h"
#include "MagiciteGameDrawLine.h"

USING_NS_CC;

MagiciteGameDrawLayer::MagiciteGameDrawLayer()
{

}

MagiciteGameDrawLayer::~MagiciteGameDrawLayer()
{
    clear();
}

bool MagiciteGameDrawLayer::init()
{
    if (!Layer::init())
    {
        return false;
    }

    _drawNode = DrawNode::create();
    this->addChild(_drawNode);

    return true;
}

void MagiciteGameDrawLayer::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags)
{
    if (!_lineList.empty())
    {
        for (auto &p : _lineList)
        {
            _drawNode->drawSegment(p->getPointA(),p->getPointB(),p->getWidth(),p->getColor());
        }
    }
}

MagiciteGameDrawLine* MagiciteGameDrawLayer::createLine(const cocos2d::Vec2& pointA,
    const cocos2d::Vec2& pointB,
    float width,
    const cocos2d::Color4F& color)
{
    auto ptr = MagiciteGameDrawLine::create(pointA, pointB, width, color);
    if (ptr != nullptr)
    {
        _lineList.push_back(ptr);
        return ptr;
    }
    else
    {
        CC_SAFE_DELETE(ptr);
        return nullptr;
    }
}

void MagiciteGameDrawLayer::destroyLine(MagiciteGameDrawLine* line)
{
    auto iter = std::find(_lineList.begin(), _lineList.end(), line);
    if (iter != _lineList.end())
    {
        _lineList.erase(iter);
        CC_SAFE_DELETE(line);
    }
    _drawNode->clear();
}

void MagiciteGameDrawLayer::clear()
{
    for (auto &ptr : _lineList)
    {
        CC_SAFE_DELETE(ptr);
    }
}